import axios, { AxiosInstance, AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import { ElMessage } from 'element-plus';
import {fatchDataState} from '../store/fetchData';
import domain from './domain.js';
const fatchDataLoading = fatchDataState()

const service: AxiosInstance = axios.create({
    baseURL: domain.fetchUrl,
    timeout: 20000
});
// service.defaults.headers.common['token'] = userInfo ? userInfo.token_key : '';

service.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token')
        if(token) {
            config.headers.token = token
        }
        return config;
    },
    (error: AxiosError) => {
        return Promise.reject();
    }
);

service.interceptors.response.use(
    (response: AxiosResponse) => {
        fatchDataLoading.handleChangeState(false)
        if (response.status === 200) {
            const pathname = window.location.pathname
            if (response.data && response.data.code == '904') {
                localStorage.clear()
                setTimeout(() => {
                    if (pathname.indexOf('login') < 0) {
                         window.location.href = `/login`
                    } else {
                         window.location.href = `/login?url=${pathname}`
                    }
                   
                }, 100)
                
            }
            if (response.data && response.data.code != '1000') {
                ElMessage.error(response.data.msg)
            }
            return response.data;
        } else {
            Promise.reject();
        }
    },
    (error: AxiosError) => {
        console.log(error);
        return Promise.reject();
    }
);

export default service;
